package org.cmy.service;

import org.cmy.mapper.UserMapper;
import org.cmy.po.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    public CustomUserDetailsService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("获取用户信息");
        User user = userMapper.findByUsername(username);
        if (user == null) throw new UsernameNotFoundException("User not found");

        user.setRoles(userMapper.findRolesByUserId(user.getId()));
        user.setPermissions(userMapper.findPermissionsByUserId(user.getId()));

        Set<SimpleGrantedAuthority> authorities = Stream.concat(
                user.getRoles().stream().map(SimpleGrantedAuthority::new),
                user.getPermissions().stream().map(SimpleGrantedAuthority::new)
        ).collect(Collectors.toSet());

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .disabled(!user.getEnabled())
                .build();
    }
}